package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.DestinationQuery;
import cn.wolfcode.wolf2w.repository.DestinationRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IRegionService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
//@Transactional mongodb事务必须复制集方式
public class DestinationServiceImpl implements IDestinationService {

    @Autowired
    private DestinationRepository repository;
    @Autowired
    private IRegionService regionService;
    @Autowired
    private MongoTemplate template;
    @Override
    public void save(Destination destination) {
        destination.setId(null);
        repository.save(destination);
    }

    @Override
    public void update(Destination destination) {
        repository.save(destination);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Destination get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Destination> list() {
        return repository.findAll();
    }



    @Override
    public List<Destination> queryDestByRegionId(String rid) {

        //通过区域id查询区域对象,
        Region region = regionService.get(rid);


        //获取对象挂载的目的id集合
        List<String> ids = region.getRefIds();

        //通过id集合查询目的地集合
        //sql: select * from dest where id in (1,2,3...)

        //spring-data
        return repository.findByIdIn(ids);
    }
    @Override
    public void saveOrUpdate(Destination destination) {
        if(StringUtils.hasLength(destination.getId())){
            this.update(destination);
        }else{
            this.save(destination);
        }
    }


    @Override
    public Page<Destination> query(DestinationQuery qo) {
        Query query = new Query();
        //条件
        if(StringUtils.hasLength(qo.getKeyword())){
            query.addCriteria(Criteria.where("name").regex(qo.getKeyword()));
        }
        if(StringUtils.hasLength(qo.getParentId())){
            query.addCriteria(Criteria.where("parentId").is(qo.getParentId()));
        }else{
            //为null
            query.addCriteria(Criteria.where("parentId").is(null));
        }

        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.ASC, "_id");

        return DBHelper.query(template, Destination.class, query, pageable);
    }

    //导航（土司）
    @Override
    public List<Destination> queryToasts(String parentId) {
        List<Destination> list = new ArrayList<>();
        //导航查询
        //循环两种方法
        //1：while循环(!父对象为null)
        //2：递归：方法自己调用自己
        this.createToast(list, parentId);

        Collections.reverse(list);  //集合翻转

        return list;
    }
    //用于创建toast对象
    private void createToast(List<Destination> list, String parentId) {
         //递归前提自己能出来
        //parentID为null时候, 不执行
        if(!StringUtils.hasLength(parentId)){
            return;
        }
        //dest广州
        Destination dest = this.get(parentId);
        //塞进去广州
        list.add(dest);
        //判断其有无老爸
        if(StringUtils.hasLength(dest.getParentId())){
            //有，接着遍历
            createToast(list, dest.getParentId());
        }
    }

    @Override
    public List<Destination> queryDestByRegionIdForApi(String regionId) {
       //目的地集合
        List<Destination> list = new ArrayList<>();

        //第一层：国内区域挂载的目的地
        if("-1".equals(regionId)){
            //是----》查询:中国所有省份
            //db.destination.find{name:"中国"}
            list = repository.findByParentName("中国");
        }else{

            //区域:非国内
            list = this.queryDestByRegionId(regionId);
        }

        //第二层：目的地下的子目的地
        //台湾  香港
        for (Destination dest : list) {



            //jpa 查询方法可以添加分页, 排序操作
            //分为前端与后端，前端加更多，在显示
            //后端对应的儿子只显示5个
            //第一种方式
            //List<Destination> children = repository.findByParentId(dest.getId());
            //约定: 查询子目的地子需要查询前5个
            /*if(children.size() > 5){
                children = children.subList(0, 5);
            }*/

            //第二种方式，通过分页，每页显示5页，只取第一页
            /**public static PageRequest of(int page, int size, Direction direction, String... properties) {
             *return of(page, size, Sort.by(direction, properties));}
             * */
            Pageable pageable =
                    PageRequest.of(0, 5, Sort.Direction.ASC, "_id");
//domain中共享数据的
            //台湾下的儿子
            List<Destination> children = repository.findByParentId(dest.getId(), pageable);
            dest.setChildren(children);
        }
        return list;
    }


    @Override
    public Destination queryName(String name) {
        return repository.findByName(name);
    }

}
